<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-07-01 10:26:03
 * @Description: 拼多多订单处理流程
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-07-06 16:57:28
 * @FilePath: /qingshanERP/app/Http/Controllers/Console/QingShanERP/OrderPddController.php
 */

namespace App\Http\Controllers\Console\QingShanERP;

use DB;
use Validator;
use Illuminate\Http\Request;
use App\Customize\PddRequest;
use App\Models\QingShanERP\Order;
use App\Http\Controllers\Controller;
use App\Models\QingShanERP\OrderLog;
use App\Models\QingShanERP\Supplier;
use App\Models\QingShanERP\OrderGood;
use App\Models\QingShanERP\GoodSupplier;
use App\Models\QingShanERP\GoodSpecSupplier;
use App\Models\QingShanERP\Logistics;
use App\Models\QingShanERP\OrderPddTracking;

class OrderPddController extends Controller
{
    public function getList(Request $req)
    {
        try {
            $page = $req->input('page', 0);
            $size = $req->input('size', 10);
            $shopid = $req->input('shopid', '');
            $supplier_id = $req->input('supplier_id', '');
            $confirm_status = $req->input('confirm_status', '');
            $order_status = $req->input('order_status', '');
            $after_sales_status = $req->input('after_sales_status', '');
            $supplier_order_status = $req->input('supplier_order_status', '');
            $remark_tag = $req->input('remark_tag', '');
            $key = $req->input('key', '');
            $tracking_number = $req->input('tracking_number', '');
            $list = Order::with(['shop' => function ($q) {
                        $q->select('id', 'shopname');
                    }, 'supplier', 'pdd','goods','supplier_staff'])->where(function ($q) use ($shopid) {
                        if ($shopid != '') {
                            $q->where('shop_id', $shopid);
                        }
                    })->where(function ($q) use ($supplier_id) {
                        if ($supplier_id != '') {
                            $q->where('supplier_id', $supplier_id);
                        }
                    })->where(function ($q) use ($remark_tag) {
                        if ($remark_tag != '') {
                            $q->where('remark_tag','!=', $remark_tag);
                        }
                    })->where(function ($q) use ($confirm_status) {
                        if ($confirm_status != '') {
                            $q->where('confirm_status', $confirm_status);
                        }
                    })->where(function ($q) use ($order_status) {
                        if ($order_status != '') {
                            $q->where('order_status', $order_status);
                        }
                    })->where(function ($q) use ($after_sales_status) {
                        if ($after_sales_status == '0') {
                            $q->where('after_sales_status', 0);
                        }elseif ($after_sales_status > 0) {
                            $q->where('after_sales_status','>', 0);
                        }
                    })->where(function ($q) use ($supplier_order_status) {
                        if ($supplier_order_status != '') {
                            $q->where('supplier_order_status', $supplier_order_status);
                        }
                    })->where(function ($q) use ($key) {
                        if ($key != '') {
                            $q->where('order_sn', 'like', '%' . $key . '%');
                        }
                    })->where(function ($q) use ($tracking_number) {
                        if ($tracking_number != '') {
                            $q->where('tracking_number', $tracking_number);
                        }
                    })->where('del_flag', 0)->offset(($page - 1) * $size)->limit($size)->orderBy('confirm_time', 'desc')->get();
            $count = Order::where(function ($q) use ($shopid) {
                        if ($shopid != '') {
                            $q->where('shop_id', $shopid);
                        }
                    })->where(function ($q) use ($supplier_id) {
                        if ($supplier_id != '') {
                            $q->where('supplier_id', $supplier_id);
                        }
                    })->where(function ($q) use ($remark_tag) {
                        if ($remark_tag != '') {
                            $q->where('remark_tag', '!=', $remark_tag);
                        }
                    })->where(function ($q) use ($confirm_status) {
                        if ($confirm_status != '') {
                            $q->where('confirm_status', $confirm_status);
                        }
                    })->where(function ($q) use ($order_status) {
                        if ($order_status != '') {
                            $q->where('order_status', $order_status);
                        }
                    })->where(function ($q) use ($after_sales_status) {
                        if ($after_sales_status == '0') {
                            $q->where('after_sales_status', 0);
                        } elseif ($after_sales_status > 0) {
                            $q->where('after_sales_status', '>', 0);
                        }
                    })->where(function ($q) use ($supplier_order_status) {
                        if ($supplier_order_status != '') {
                            $q->where('supplier_order_status', $supplier_order_status);
                        }
                    })->where(function ($q) use ($key) {
                        if ($key != '') {
                            $q->where('order_sn', 'like', '%' . $key . '%');
                        }
                    })->where(function ($q) use ($tracking_number) {
                        if ($tracking_number != '') {
                            $q->where('tracking_number', $tracking_number);
                        }
                    })->where('del_flag', 0)->count();
            $res = ['list' => $list, 'total' => $count];
            return $this->resData(200, '获取数据成功...', $res);
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 分配供应商
    public function postSupplier(Request $request){
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->input(), [
                'supplier_id' => 'required|integer',
                'order_ids' => 'required|array',
            ]);
            $attrs = array(
                'supplier_id' => '供应商',
                'order_ids' => '订单'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                DB::rollback();
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $supplier_id = $request->input('supplier_id');
            $supplier = Supplier::where('status',1)->where('del_flag',0)->findOrFail($supplier_id);
            if (is_null($supplier)) {
                DB::rollback();
                return $this->resData(400, '供应商不存在');
            }
            $order_ids = $request->input('order_ids',[]);
            if (!count($order_ids)) {
                DB::rollback();
                return $this->resData(400, '请选择要操作的订单');
            }
            // 看下是不是都没有分配，有分配过的不允许重新分配
            $order_status = Order::whereIn('id', $order_ids)->where('order_status', '!=',1)->count();
            if ($order_status) {
                DB::rollback();
                return $this->resData(400, '存在已发货订单，请重新选择');
            }
            $hav = Order::whereIn('id',$order_ids)->where('supplier_id','!=',0)->count();
            if ($hav) {
                DB::rollback();
                return $this->resData(400, '请选择未分配供应商的订单');
            }
            // 开始更新
            Order::whereIn('id', $order_ids)->update(['supplier_id'=>$supplier_id]);
            $all_order = Order::with('goods')->whereIn('id', $order_ids)->get();
            $all_supplier_spec = GoodSpecSupplier::where('del_flag',0)->where('supplier_id', $supplier_id)->get();
            $all_supplier = GoodSupplier::where('del_flag', 0)->where('supplier_id', $supplier_id)->get();
            // 记录日志
            foreach ($all_order as $o) {
                OrderLog::create(['order_id'=>$o->id,'user_type'=>1,'user_id'=>$request->req_user->id, 'log_name'=>'分配供应商','url'=> 'c-api/order/pddsupplier','data'=>$supplier_id]);
                // 订单商品对应信息更新
                $supplier_price = 0;
                $shipping = 0;
                foreach ($o->goods as $g) {
                    $supplier_spec = $all_supplier_spec->where('good_spec_id',$g->good_spec_id)->first();
                    $supplier_name = $all_supplier->where('good_id', $g->good_id)->first();
                    if (is_null($supplier_spec)) {
                        DB::rollback();
                        return $this->resData(400, $g->good_spec_name.' : 没有对应的供应商规格...');
                    }
                    OrderGood::where('id',$g->id)->update(['good_supplier_name'=> is_null($supplier_name) ? '无' : $supplier_name->good_name, 'good_supplier_spec_name'=>$supplier_spec->spec, 'supplier_price'=>$supplier_spec->price, 'shipping' => $supplier_spec->shipping]);
                    $supplier_price = $supplier_price + $g->goods_count * $supplier_spec->price;
                    $shipping = $shipping + $g->goods_count * $supplier_spec->shipping;
                }
                Order::where('id',$o->id)->update(['supplier_price'=> $supplier_price, 'shipping'=> $shipping]);
            }
            DB::commit();
            return $this->resData(200, '分配成功...');
        } catch (\Throwable $th) {
            DB::rollback();
            return $this->resData(500, '添加失败，请重新操作...', $th->getMessage());
        }
    }
    // 发货、重发 pdd.logistics.online.send , 要记录下日志，重发需要限制在24小时内
    public function postTrack(Request $request){
        try {
            $validator = Validator::make($request->input(), [
                'supplier_staff_id' => 'required|integer',
                'order_id' => 'required|integer',
                'order_track_id' =>'required|integer',
            ]);
            $attrs = array(
                'supplier_staff_id' => '员工',
                'order_id' => '订单号',
                'order_track_id' => '面单ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            // 查单号
            // $all['order_id'] = '12585';
            $logistics = OrderPddTracking::where('id', $all['order_track_id'])->first();
            if (is_null($logistics) || $logistics->status == 0 || $logistics->order_id != $all['order_id'] || $logistics->del_flag == 1) {
                return $this->resData(400, '此面单号不可用...');
            }
            $order = Order::with('supplier')->where('id',$all['order_id'])->first();
            if (is_null($order)) {
                return $this->resData(400, '没有此订单...');
            }
            if ($order->supplier_order_status == 1 && strtotime($order->shipping_time) < time() - 3600*24) {
                return $this->resData(400, '订单发货已经超过24小时，不能修改订单号...');
            }
            // 拼多多接口发货
            $params['access_token'] = PddRequest::getToken($order->shop_id);
            if (is_null($params['access_token'])) {
                return $this->resData(400, '此门店授权已过期，请先重新授权...');
            }
            $params['logistics_id'] = $logistics->logistics_id;
            $params['order_sn'] = $order->order_sn;
            $params['tracking_number'] = $logistics->tracking_number;
            // 供应商的退货地址
            $params['refund_address_id'] = $order->supplier->refund_address_id;
            $result = PddRequest::request('pdd.logistics.online.send', $params);
            // 请求成功
            if(isset($result['logistics_online_send_response']) && $result['logistics_online_send_response']['is_success']){
                // 更新订单信息，供货商发货
                Order::where('id', $all['order_id'])->update(['supplier_staff_id' => $all['supplier_staff_id'], 'supplier_order_status' => 1, 'logistics_id' => $logistics->logistics_id, 'tracking_number' => $logistics->tracking_number, 'shipping_time'=>date('Y-m-d H:i:s')]);
                OrderPddTracking::where('id', $logistics->id)->update(['status'=>0]);
                // 如果是换单号，删掉以前那个
                if (!is_null($order->tracking_number)) {
                    OrderPddTracking::where('tracking_number', $order->tracking_number)->update(['del_flag' => 1]);
                }
                return $this->resData(200, '发货成功...');
            }else{
                return $this->resData(400, '拼多多发货失败，请稍后重发...',$result);
            }
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 补发 pdd.order.upload.extra.logistics , 要记录下日志
    public function reissueTrack(Request $request){
        try {
            $validator = Validator::make($request->input(), [
                'supplier_staff_id' => 'required|integer',
                'order_id' => 'required|integer',
                'order_track_id' => 'required|integer',
            ]);
            $attrs = array(
                'supplier_staff_id' => '员工',
                'order_id' => '订单号',
                'order_track_id' => '面单ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            // 查单号
            $logistics = OrderPddTracking::where('id', $all['order_track_id'])->first();
            if (is_null($logistics) || $logistics->status == 0 || $logistics->order_id != $all['order_id'] || $logistics->del_flag == 1) {
                return $this->resData(400, '此面单号不可用...');
            }
            $order = Order::where('id', $all['order_id'])->first();
            if (is_null($order)) {
                return $this->resData(400, '没有此订单...');
            }
            // 拼多多接口发货
            $params['access_token'] = PddRequest::getToken($order->shop_id);
            if (is_null($params['access_token'])) {
                return $this->resData(400, '此门店授权已过期，请先重新授权...');
            }
            // 开始接口发
            $params['order_sn'] = $order->order_sn;
            $params['extra_track_list'] = ['shipping_id' => $logistics->logistics_id, 'tracking_number' => $logistics->tracking_number];
            $result = PddRequest::request('pdd.order.upload.extra.logistics', $params);
            // 请求成功
            if (isset($result['upload_extra_logistics_response']) && $result['upload_extra_logistics_response']['success']) {
                // 更新补发信息进附表
                // $insert = [];
                // foreach ($all['logistics'] as $v) {
                //     $insert[] = ['order_id' => $all['order_id'], 'supplier_staff_id' => $all['supplier_staff_id'], 'logistics_id' => $v['logistics_id'], 'tracking_number' => $v['tracking_number'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
                // }
                // OrderPddTracking::insert($insert);
                OrderPddTracking::where('id',$logistics->id)->update(['status' => 0]);
                return $this->resData(200, '补发货成功...');
            } else {
                return $this->resData(400, '拼多多补发货失败，请稍后重发...',$result);
            }
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 补发 pdd.order.upload.extra.logistics , 要记录下日志
    public function reissueTrackNumber(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'supplier_staff_id' => 'required|integer',
                'order_id' => 'required|integer',
                'logistics' => 'required|array',
            ]);
            $attrs = array(
                'supplier_staff_id' => '员工',
                'order_id' => '订单号',
                'logistics' => '运单信息',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            // 查单号
            // $all['order_id'] = '12585';
            $order = Order::where('id', $all['order_id'])->first();
            if (is_null($order)) {
                return $this->resData(400, '没有此订单...');
            }
            // 拼多多接口发货
            $params['access_token'] = PddRequest::getToken($order->shop_id);
            if (is_null($params['access_token'])) {
                return $this->resData(400, '此门店授权已过期，请先重新授权...');
            }
            // 开始接口发
            $params['order_sn'] = $order->order_sn;
            $params['extra_track_list'] = $all['logistics'];
            $result = PddRequest::request('pdd.order.upload.extra.logistics', $params);
            // 请求成功
            if (isset($result['upload_extra_logistics_response']) && $result['upload_extra_logistics_response']['success']) {
                // 更新补发信息进附表
                $insert = [];
                foreach ($all['logistics'] as $v) {
                    $wp_code = Logistics::where('logistics_id',$v['logistics_id'])->where('type',4)->where('del_flag',0)->where('status',1)->value('logistics_code');
                    $insert[] = ['order_id' => $all['order_id'], 'supplier_staff_id' => $all['supplier_staff_id'], 'logistics_id' => $v['logistics_id'], 'wp_code' => $wp_code, 'tracking_number' => $v['tracking_number'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
                }
                OrderPddTracking::insert($insert);
                return $this->resData(200, '补发货成功...');
            } else {
                return $this->resData(400, '拼多多补发货失败，请稍后重发...', $result);
            }
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 获取电子面单加密信息 pdd.waybill.get
    public function postWaybill(Request $request){
        try {
            $validator = Validator::make($request->input(), [
                'supplier_staff_id' => 'required|integer',
                'order_id' => 'required|integer',
                'wp_code' => 'required',
            ]);
            $attrs = array(
                'supplier_staff_id' => '员工',
                'order_id' => '订单号',
                'wp_code' => '物流公司',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $supplier_staff_id = $all['supplier_staff_id'];
            // 查单号
            // $all['order_id'] = '12585';
            $order = Order::with(['shop', 'supplier','pdd','goods'])->where('id', $all['order_id'])->first();
            if (is_null($order)) {
                return $this->resData(400, '没有此订单...');
            }
            if ($order->supplier_id == '0') {
                return $this->resData(400, '请先分配供应商...');
            }
            $userid = str_replace('pdd','', $order->shop->shopid);
            $all_numbers = OrderPddTracking::where('order_id',$all['order_id'])->where('del_flag',0)->get();
            if($all_numbers->count() > 0){
                $modules = [];
                foreach ($all_numbers as $a) {
                    $modules[] = json_decode($a->waybill,true);
                }
                return $this->resData(200, '获取成功', ['userid' => $userid, 'waybill' => $modules]);
            }
            // 请求面单号
            $params['access_token'] = PddRequest::getToken($order->shop_id);
            if (is_null($params['access_token'])) {
                return $this->resData(400, '此门店授权已过期，请先重新授权...');
            }
            // 物流公司Code
            $wp_code = $all['wp_code'];
            // 发货人信息，应该在供应商下加入此信息，通过订单来找这个信息
            $sender = [
                'name' => '鸿阔退货',
                'mobile' => '18903187330',
                'address' => [
                    'province' => '河北省',
                    'city' => '衡水市',
                    'district' => '桃城区',
                    'detail' => '邓庄中学对过',
                ]
            ];
            // $sender = [
            //     'name' => $order->supplier->name,
            //     'mobile' => $order->supplier->phone,
            //     'address' => [
            //         'province' => $order->supplier->province,
            //         'city' => $order->supplier->city,
            //         'district' => $order->supplier->district,
            //         'detail' => $order->supplier->detail,
            //     ]
            // ];
            // 请求面单信息，数量限制为10
            $items = [];
            foreach ($order->goods as $g) {
                $items[] = ['count'=>$g->goods_count, 'name'=>$g->good_supplier_spec_name];
            }
            $total_count = $order->goods->sum('goods_num');
            $trade_order_info_dtos = [
                [
                    'object_id' => time(),
                    'template_url' => config('pdd.template_url'),
                    'user_id' => $userid,
                    'order_info' => [
                        // 订单平台、单号
                        'order_channels_type' => 'PDD',
                        'trade_order_list' => [$order->order_sn],
                    ],
                    'package_info' => [
                        // 子母件总包裹数 $order->goods->sum('goods_num')
                        'total_packages_count' => $total_count,
                        // 对应供应商产品名与规格名
                        'items'    =>   $items
                    ],
                    'recipient' => [
                        'name' => $order->pdd->receiver_name,
                        'mobile' => $order->pdd->receiver_phone,
                        'address' => [
                            'province' => $order->pdd->province,
                            'city' => $order->pdd->city,
                            'district' => $order->pdd->town,
                            'town' => $order->pdd->town,
                            'detail' => $order->pdd->receiver_address,
                        ]
                    ],
                ]
            ];
            $params['param_waybill_cloud_print_apply_new_request'] = ['sender' => $sender, 'wp_code' => $wp_code, 'trade_order_info_dtos' => $trade_order_info_dtos];
            // dd($params);
            $result = PddRequest::request('pdd.waybill.get', $params);
            // dd($result);
            if (isset($result['pdd_waybill_get_response'])) {
                // 记录面单信息，重新打印用
                $insert = [];
                $date = date('Y-m-d H:i:s');
                $logistics_id = Logistics::where('logistics_code',$wp_code)->where('type',4)->where('status', 1)->where('del_flag',0)->value('logistics_id');
                foreach ($result['pdd_waybill_get_response']['modules'] as $v) {
                    $insert[] = ['order_id'=> $all['order_id'], 'supplier_staff_id'=> $supplier_staff_id, 'logistics_id'=> $logistics_id,'wp_code'=> $wp_code, 'tracking_number'=>$v['waybill_code'],'waybill'=>json_encode($v), 'created_at'=>$date,'updated_at'=>$date];
                }
                OrderPddTracking::insert($insert);
                return $this->resData(200, '获取成功', ['userid'=> $userid,'waybill'=> $result['pdd_waybill_get_response']['modules']]);
            }
            else {
                return $this->resData(400, '拼多多获取面单失败，请稍后再试...');
            }
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 那所有面单号
    public function postOrderTrack(Request $request){
        try {
            $validator = Validator::make($request->input(), [
                'order_id' => 'required|integer',
            ]);
            $attrs = array(
                'order_id' => '订单号',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            // 查单号
            $logistics = OrderPddTracking::where('order_id', $all['order_id'])->where('del_flag',0)->get();
            return $this->resData(200, '发货成功...', $logistics);
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
}
